EcmaScript5
function(x){return x+1}EcmaScript6
x=>x+1 -- HM(Hindley-Milner) type signature
liftM :: (Monad m) => (a -> b) -> m a -> m b
-- ^type restrict ^function ^ ^return
-- ^curry^ [1,2,3].map(x=>x+1)
// => [2,3,4]
[1,2,3].filter(x=>x/2==0)
// => [2]
[1,2,3].reduce((acc,n)=>acc+n)
// => 6 ["hello", "world"].map(x=>x.toUpperCase())
// => ["HELLO", "WORLD"]functor is mapable!
"hello" + "world" // <-- concat
// => "helloworld"
"hello" + "" // <-- identity
// => "hello"
("hello" + "world") + "!" == "hello" + ("world" + "!") // <-- associative
// => trueMonoid is concatable!
Method -> Function
map(x=>x.toUpperCase(), ["hello", "world"])
concat("hello", "world")
concat("empty", "")A monad is just a monoid in the category of endofunctors, what's the problem?
"A monad is just a concatable in mapable Type, what's the problem?"
flat(Maybe[Maybe[(Maybe[T])]]) == flat(Maybe[(Maybe[Maybe[T]])])
join (Maybe[T]) == Maybe [Maybe[T]]
concat(Maybe[ Maybe[Maybe[T]] ]) == concat(join(Maybe[Maybe[T]])) == Maybe[Maybe[T]]
uT(x) -> flat(T(x))
T(ux) -> lift(flat, x)
nT(x) -> join(T(x))
T(nx) -> map(join, T(x))
liftM :: (Monad m) => (a -> b) -> m a -> m b const when = require('when')
let readJSON = when.lift(JSON.parse)
readJSON(when('{hello: "world"}'))
.then(x=>console.log(x))
.catch(e=>console.error(e.message));
// => Unexpected token h in JSON at position 1as I said promise is smart monad
readJSON('{"hello": "world"}')
.then(x=>console.log(x))
.catch(e=>console.error(e.message));
// => { hello: 'world' }or simply try something and wrap result in Promise
try(JSON.parse, '{hello: "world"}')
.then(x=>console.log(x))
.catch(e=>console.error(e.message));
// => Unexpected token h in JSON at position 1 foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a const Type = require('union-type')
const T = () => true;
const Maybe = Type({Just: [T], Nothing: []});
Maybe.prototype.map = function(fn) {
return Maybe.case({
Nothing: () => Maybe.Nothing(),
Just: (v) => Maybe.Just(fn(v))
}, this);
};
... let futureWorld = new Promise(resolve=>{
setTimeout(()=>resolve("world"), 1000)
}) futureWorld
.then(world=>new Promise(resolve=>{
setTimeout(()=>resolve("hello"+world), 1000)
}))
.then(x=>console.log(x))
// 2secs later => helloworldthen is flatMapthen is map| Single Item | Multiple Items | |
|---|---|---|
| synchronous | getData():T | getData():List[T] |
| asynchronous | getData():Future[T] | getData():Observable[T] |
[[https://dl.dropboxusercontent.com/u/1150365/futurama/neat.gif]]
Thanks